// request.js 中对axios 做二次封装
import store from "@/store";
import axios from "axios";
// 创建一个请求的服务
const http = axios.create({
    //设置请求地址的base地址
    baseURL: 'http://shop.bluej.cn/api',
    // 设置请求的时间 单位 ms
    timeout: 5000
})

// 拦截器
http.interceptors.request.use(config => {
    let token = store.state.user.token
    if (token) {
        return config
    }
})


// post接口
export const post = (url, data) => {
    return new Promise((resolve, reject) => {
        http.post(url, data, {
            headers: {
                "Content-Type": "application/json",
                "x-token": sessionStorage.getItem('token')
            },
        })
            .then(res => {
                resolve(res.data)
                console.log(res);
            })
            .catch(err => {
                reject(err)
            })
    })
}
// post头像上传
export const poster = (url, data) => {
    return new Promise((resolve, reject) => {
        http.post(url, data, {
            headers: {
                "Content-Type": "multipart/form-data",
                "x-token": sessionStorage.getItem('token')
            },
        })
            .then(res => {
                resolve(res.data)
                console.log(res);
            })
            .catch(err => {
                reject(err)
            })
    })
}
// get
export const getNotHeader = (url, params = {}) => {
    return new Promise((resolve, reject) => {
        http.get(url, { params }).then(
            (response) => {
                resolve(response.data);
            },
            (err) => {
                reject(err);
            }
        );
    });
};

// 获取购物车列表信息接口
export const get = (url, params = {}) => {
    return new Promise((resolve, reject) => {
        http.get(url, {
            headers: {
                "x-token": sessionStorage.getItem('token') || null
            }
        })
            .then(
                (response) => {
                    resolve(response.data);
                },
                (err) => {
                    reject(err);
                }
            );
    });
};


// delete请求
export const delcar = (url, token) => {
    return new Promise((resolve, reject) => {
        http.delete(url, {
            headers: {
                "x-token": token
            }
        }).then(
            (response) => {
                resolve(response.data);
            },
            (err) => {
                reject(err);
            }
        );
    });
};

// PUT请求
export const addToCart = (url, token, data) => {
    return new Promise((resolve, reject) => {
        http.put(url, data, {
            headers: {
                'Content-Type': 'application/json',
                "x-token": token
            }
        }).then(
            (response) => {
                resolve(response.data);
            },
            (err) => {
                reject(err);
            }
        );
    });
};



